package wty;

import slh.ConSql;
import slh.comment.commentDao;
import slh.favourite.FavouriteDao;
import wty.Bee.User;
import wty.Bee.UserDao;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;

@WebServlet("/wty/sendUserMsg")
public class SendUserCenterMsgServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        try {
            System.out.println("我马上发送用户数据！");
            req.setCharacterEncoding("UTF-8");
            res.setContentType("application/json;charset=UTF-8");

            // 获取用户ID
            String userId = (String) req.getSession().getAttribute("userId");
            if (userId == null) {
                res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                res.getWriter().print(new JSONObject()
                        .put("success", false)
                        .put("msg", "用户未登录")
                        .toString());
                return;
            }

            // 获取用户信息
            Connection conn = ConSql.getConnection();
            FavouriteDao favouriteDao = new FavouriteDao(conn);
            ArrayList<String> favorites = favouriteDao.getUserFavoriteContent(
                    userId
            );

            commentDao commentDao = new commentDao();
            ArrayList<String> comments = commentDao.getUserAllCommentsText(
                    userId
            );


            UserDao userDao = new UserDao();
            User user = userDao.selectById(userId);

            log("a");
            if (user == null) {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
                res.getWriter().print(new JSONObject()
                        .put("success", false)
                        .put("msg", "用户不存在")
                        .toString());
                return;
            }

            // 构建用户信息JSON
            JSONObject userJson = new JSONObject();
            userJson.put("userId", user.getUserid());
            userJson.put("username", user.getUsername());
            userJson.put("email", user.getEmail());
            userJson.put("phone", user.getPhone());

//            userJson.put("avatar", user.getAvatar());
            // 添加头像处理（Base64编码）
            if (user.getAvatar() != null && user.getAvatar().length > 0) {
                String avatarBase64 = Base64.getEncoder().encodeToString(user.getAvatar());
                userJson.put("avatar", "data:image/png;base64," + avatarBase64); // 根据实际格式调整MIME类型
            } else {
                userJson.put("avatar", JSONObject.NULL); // 直接赋值为null
            }


            userJson.put("gender", user.getGender());
            userJson.put("birthday", user.getBirthday() != null ? user.getBirthday().toString() : null);
            userJson.put("province", user.getProvince());
            userJson.put("city", user.getCity());
            userJson.put("role", user.getRole());

            // 返回成功响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", true);
            responseJson.put("user", userJson);
            responseJson.put("favorites", favorites);
            responseJson.put("comments", comments);
            responseJson.put("msg", "用户信息获取成功");

            res.getWriter().print(responseJson.toString());

        } catch (Exception e) {
            e.printStackTrace();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            res.getWriter().print(new JSONObject()
                    .put("success", false)
                    .put("msg", "服务器错误: " + e.getMessage())
                    .toString());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("正在使用get方法调用");
        doPost(req, resp);
    }
}
